package com.mmy.study.service;

import cn.hutool.crypto.digest.MD5;
import com.mmy.study.dao.User;
import com.mmy.study.mapper.RolesMapper;
import com.mmy.study.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserService {
    @Autowired
    RolesMapper rolesMapper;
    @Autowired
    UserMapper userMapper;

    public User loadUserByUsername(String s) {
        User user = userMapper.loadUserByUsername(s);
        log.info("user is : " + user.toString());
        if(user == null) {
            // 说明没有找到
            return null;
        }
        return user;
    }
    public User getById(long id) {
        User user = userMapper.getById(id);
        if(user == null) {
            // 说明没有找到
            return null;
        }
        return user;
    }
    public Integer reg(User user) {

        User loadUserByUsername = userMapper.loadUserByUsername(user.getUsername());
        if (loadUserByUsername != null) {
            return 1;
        }

        //插入用户,插入之前先对密码进行加密
        user.setPassword(MD5.create().digestHex(user.getPassword()));
        user.setEnabled(true);//用户可用
        long result = userMapper.reg(user);
        //配置用户的角色，默认都是普通用户
        String[] roles = new String[]{"2"};
        int i = rolesMapper.addRoles(roles, user.getId());
        boolean b = i == roles.length && result == 1;
        if (b) {
            return 0;
        } else {
            return 2;
        }
    }
}
